<template>
  <view>
    <u-form
      :model="model"
      :rules="rules"
      ref="form"
      labelPosition="top"
      labelWidth="auto"
      :labelStyle="{
        fontSize: '14px',
        color: '#B2B2B2',
        lineHight: '20px',
      }"
    >
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="单据编号" prop="billNo" required>
          <u--input v-model="model.billNo" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请人" prop="proposer" required>
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.proposer"
            placeholder="请选择申请人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.proposer"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="申请部门" prop="proposerDeptId" required>
          <h-select-depart-input
            disabled
            v-model="model.proposerDeptId"
            :departName="model.proposerDeptText"
            placeholder="请选择部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.proposerDeptText"
          ></h-select-depart-input>
        </u-form-item>
        <u-form-item label="申请时间" required>
          <u--input v-model="model.createTime" disabled></u--input>
        </u-form-item>
        <u-form-item label="所属团队" prop="teamId" required>
          <h-select-team-input
            style="width: 100%"
            v-model="model.teamId"
            objectField="model.teamId"
            placeholder="请选择费用所属团队"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :tdlx="3"
            @input="teamBack"
          ></h-select-team-input>
        </u-form-item>
        <u-form-item label="申请公司" prop="applyCompany" required>
          <h-select-company-input
            style="width: 100%"
            v-model="model.applyCompany"
            border="surround"
            placeholder="请选择公司"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.applyCompany"
            @input="companyBack"
          ></h-select-company-input>
        </u-form-item>

				<u-form-item label="费用所属年度" prop="teamYear" v-if="model.teamYear=='2023'">
					<h-select-input-tag disabled style="width: 100%" dictName="tdnd_type" v-model="model.teamYear"
						placeholder="请选择费用所属年度" border="surround" suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"></h-select-input-tag>
				</u-form-item>
        <u-form-item label="备注" prop="remark">
          <u--textarea v-model="model.remark" :confirm-type="null" maxlength="500" count placeholder="请输入备注"></u--textarea>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">还款明细</view>
        <view class="space-y-1 py-1">
          <u-button size="small" type="primary" @click="addForm">新增</u-button>
        </view>
        <view class="trip-form-data">
          <u-collapse ref="collapseView">
            <u-collapse-item :title="`还款表单${index + 1}`" v-for="(item, index) in formData" :key="index">
              <SplitFormInfo
                formType="trip"
                :dictOptions="dictOptions"
                :item="item"
                :index="index"
                @edit="handleEditForm"
                @remove="handleRemoveForm"
              />
            </u-collapse-item>
          </u-collapse>
        </view>
        <u-popup :round="10" mode="bottom" :show="showFormModal" :closeOnClickOverlay="false" @close="closeFormModal" @open="openFormModal">
          <SplitForm
            ref="dataForm"
            :index="index"
            :teamId="model.teamId"
            :companyId="model.applyCompany"
            @submit="handleFormSubmit"
            @close="showFormModal = false"
          />
        </u-popup>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">附件信息</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
          <h-upload-file v-model="model.attachments" :isIcon="false"></h-upload-file>
          <file-list v-if="model.attachments" v-model="model.attachments" :isDelete="true"></file-list>
        </view>
      </view>

      <view class="space-x-1 px-1 btn_position">
        <u-button :disabled="isSubmit" type="primary" :plain="true" text="保存" @click="onDraft"></u-button>
        <u-button :disabled="isSubmit" type="primary" text="保存并提交" @click="onSubmit"></u-button>
      </view>
      <view style="height: 100rpx"></view>
    </u-form>
    <u-toast ref="uToast"></u-toast>
    <ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import { gainBillNo, add, edit, info, getChildData } from '@/api/finance/ErpFinanceRepaymentSlipForm'
import { initDictOptions, filterMultiDictText } from '@/utils/JDictSelectUtil.js'
import fileList from '@/pages/synergy/components/fileList.vue'
import SplitForm from './components/SplitForm.vue'
import SplitFormInfo from './components/SplitFormInfo.vue'
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗
// import Decimal from 'decimal.js'
export default {
  name: 'ErpFinanceRepaymentSlipForm',
  components: { fileList, SplitForm, SplitFormInfo, ProcessNodeConfiguration },
  data() {
    return {
      dictOptions: {},
      teamIdBackups: '',
      companyIdBackups: '',
      isSubmit: false,
      backUpApplyCompany: '',
      backUpTeamId: '',
      isReset: false,
      resetKey: '',
      basicForm: {},
      index: null,
      showFormModal: false,
      confirmModal: false,
      loading: false,
      id: '',
      model: {
        // 基本信息 - 公用
        bpmBizTitle: '',
        billNo: '',
        proposer: '',
        proposerDeptId: '',
				teamYear: '',
        createTime: '',
        applyCompany: '',
        // 基本信息 - 非公用
        teamId: '',
        remark: '',
        // 附件
        attachments: null,
      },
      formData: [],
      rules: {
        billNo: [
          {
            required: true,
            message: '请输入单据编号!',
            trigger: ['blur', 'change'],
          },
        ],
        proposerDeptId: [
          {
            required: true,
            message: '请选择申请部门!',
            trigger: ['blur', 'change'],
          },
        ],
        proposer: [
          {
            required: true,
            message: '请选择申请人!',
            trigger: ['blur', 'change'],
          },
        ],
        createTime: [
          {
            required: true,
            message: '请选择申请时间!',
            trigger: ['blur', 'change'],
          },
        ],
        isExternalEngagedEmployee: [{ required: true, message: '请选择是否外聘人员!', trigger: ['blur', 'change'] }],
        isRelProject: [{ required: true, message: '请选择是否关联项目!', trigger: ['blur', 'change'] }],
        travelReasons: [{ required: true, message: '请填写出差事由!', trigger: ['blur', 'change'] }],
        settleType: [{ required: true, message: '请选择结算方式!', trigger: ['blur', 'change'] }],
        accountName: [{ required: true, message: '请输入收款户名!', trigger: ['blur', 'change'] }],
        bankName: [{ required: true, message: '请输入收款开户行!', trigger: ['blur', 'change'] }],
        accountNo: [{ required: true, message: '请输入正确的银行卡号!', trigger: ['blur', 'change'] }],
        loanBillId: [{ required: true, message: '请选择关联借款单!', trigger: ['blur', 'change'] }],
        billCategory: [{ required: true, message: '请选择单据类型!', trigger: ['blur', 'change'] }],
        teamId: [{ required: true, message: '请选择费用所属团队!', trigger: ['blur', 'change'] }],
        applyCompany: [{ required: true, message: '请选择所属公司!', trigger: ['blur', 'change'] }],
        teamFeeCategory: [{ required: true, message: '请选择团队费用类别!', trigger: ['blur', 'change'] }],
        employeeId: [{ required: true, message: '请选择出差人员!', trigger: ['blur', 'change'] }],
      },
      flowCode: 'onl_erp_finance_repayment_slip',
      formUrl: '/erp/finance/repayment/modules/ErpFinanceRepaymentSlipForm',
      formUrlMobile: '/pages/synergy/erpFinanceRepaymentSlipForm',
      processId: '',
      beanName: 'erpFinanceRepaymentSlipServiceImpl',
    }
  },
  onLoad({ id }) {
    this.id = id || ''
  },
  created() {
    if (this.id) {
      this.initInfo()
      this.getChildData()
    } else {
      this.initForm()
      this.initBillNo()
    }
    this.initDictConfig()
  },
  computed: {
    ...mapState(['userInfo']),
    formTotal() {
      return this.formData.reduce((total, item) => total + Number(item.amount), 0).toFixed(2)
    },
  },
  methods: {
    collapseViewInit() {
      setTimeout(() => {
        this.$refs.collapseView.init()
      }, 500)
    },
    // 获取子表信息
    getChildData() {
      getChildData({ billId: this.id }).then((res) => {
        if (res.success) {
          this.formData = res.result.records || res.result
          this.collapseViewInit()
        }
      })
    },
    initDictConfig() {
      initDictOptions('erp_finance_loan_bill,bill_no,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'loanBillId', res.result)
        }
      })
      initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'teamManager', res.result)
        }
      })
    },
    teamBack(item) {
      if (!item) {
        return
      }
      const id = item.id
      //判断不为空
      if (!!this.model.teamId && id) {
        //判断团队是否变化
        if (this.teamIdBackups !== id) {
          if (this.formData.length > 0) {
            const that = this
            uni.showModal({
              title: '是否确认',
              content: '是否确认切换所属团队，此操作将会清空还款明细中已填写的所有信息？',
              cancelText: '否',
              confirmText: '是',
              success: async (res) => {
                if (res.confirm) {
                  //确认后进行改变
                  that.teamIdBackups = that.model.teamId
                  //清空子表数据
                  that.formData = []
									that.$set(that.model,'teamYear',item.tdnd)
                } else {
                  that.model.teamId = that.teamIdBackups
                }
              },
            })
          } else {
            this.teamIdBackups = id
						this.$set(this.model,'teamYear',item.tdnd)
          }
        }
      }
    },
    companyBack(item) {
      if (!item) {
        return
      }
      const id = item.id
      //判断不为空
      if (!!this.model.applyCompany && id) {
        //判断公司是否变化
        if (this.companyIdBackups !== id) {
          if (this.formData.length > 0) {
            const that = this
            uni.showModal({
              title: '是否确认',
              content: '是否确认切换申请公司，此操作将会清空还款明细中已填写的所有信息？',
              cancelText: '否',
              confirmText: '是',
              success: async (res) => {
                if (res.confirm) {
                  //确认后进行改变
                  that.companyIdBackups = that.model.applyCompany
                  //清空子表数据
                  that.formData = []
                } else {
                  that.model.applyCompany = that.companyIdBackups
                }
              },
            })
          } else {
            this.companyIdBackups = id
          }
        }
      }
    },
    handleEditForm([item, index]) {
      this.basicForm = { ...item }
      this.index = index
      this.showFormModal = true
    },
    handleRemoveForm(item) {
      this.formData = this.formData.filter((i) => i !== item)
      this.collapseViewInit()
    },
    // 获取单据编号
    async initBillNo() {
      const res = await gainBillNo({ proposer: this.userInfo.empId })
      this.model.billNo = res.result
      this.model.bpmBizTitle = this.userInfo?.employee?.name + '-' + this.model.billNo //标题
    },
    // 初始化新增需要的数据
    initForm() {
      this.model.proposer = this.userInfo.empId //当前登录人
      this.model.proposerDeptId = this.userInfo.deptId //当前登录人部门
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
    },
    async initInfo() {
      const response = await info({ id: this.id })
      const data = response?.result || {}
      this.model = Object.assign({}, data)
      this.teamIdBackups = this.model.teamId
      this.companyIdBackups = this.model.applyCompany
    },
    validateForm() {
      return this.$refs.form.validate().then(async () => {
        if (this.formData.length === 0) {
          this.$u.toast('请添加还款单信息！')
          return Promise.reject('请添加还款单信息！')
        }
        return Promise.resolve()
        // const response = await addInvoiceHandleRecordList(this.model.billNo, this.formData)
        // if (response.success) {
        //   return Promise.resolve(response)
        // } else {
        //   this.$u.toast(response.message)
        //   return Promise.reject(response.message)
        // }
      })
    },
    validateCT() {
      if (!this.model.applyCompany) {
        uni.showToast({
          title: '请选择申请公司',
          icon: 'none',
        })
        return false
      }
      if (!this.model.teamId) {
        uni.showToast({
          title: '请选择费用所属团队',
          icon: 'none',
        })
        return false
      }
      return true
    },
    addForm() {
      if (this.validateCT()) {
        this.index = null
        this.showFormModal = true
      }
    },
    closeFormModal() {
      this.$refs.dataForm.reset()
      this.basicForm = {}
      this.index = null
    },
    openFormModal() {
      this.$refs.dataForm.basicForm = this.basicForm
    },
    /**
     * 报销新增点击确认
     */
    handleFormSubmit([data, index]) {
      this.showFormModal = false
      if (typeof index === 'number') {
        this.$set(this.formData, index, { ...data })
      } else {
        this.formData.push(data)
      }
      this.collapseViewInit()
    },
    getCreateTime() {
      let createTime = this.model.createTime
      let date = createTime.substring(0, 10)
      return date.substring(0, 4) + '年' + date.substring(5, 7) + '月' + date.substring(8, 10) + '日'
    },
    setBpmBizTitle() {
      let teamName = filterMultiDictText(this.dictOptions['teamManager'], this.model.teamId + '')
      let createTime = this.getCreateTime()
      let currentReturnAmount = 0
      let dataSource = this.formData
      for (const item of dataSource) {
        currentReturnAmount = currentReturnAmount + Number(item.currentReturnAmount)
      }
      //迭代16.7 取费用所属团队-申请人-申请日期（年月日）-金额（取报销明细费用累计）
      this.model.bpmBizTitle = (teamName? teamName+ ' - ':'') + this.userInfo?.employee?.name + ' - ' + createTime + (currentReturnAmount? ' - ' + currentReturnAmount :'') //标题
    },
    async onSubmit() {
      await this.validateForm()
      this.isSubmit = true
      this.setBpmBizTitle()
      try {
        this.loading = true
        var url = ''
        if (this.id) {
          url = edit
        } else {
          url = add
        }
        this.model.slipDetailList = this.formData
        const response = await url({
          ...this.model,
        })
        if (response.success) {
          this.isSubmit = true
          if (this.id) {
            await this.getProcessList(this.id)
          } else {
            // 判断添加的时候是否有返回id值
            if (response.result) {
              await this.getProcessList(response.result)
            }
          }
          this.$refs.uToast.show({
            message: response.message,
            type: 'default',
            complete() {
              // that.isSubmit = false
            },
          })
        }
      } finally {
        this.loading = false
      }
    },
    async onDraft() {
      // await this.validateForm()

      this.isSubmit = true
      this.setBpmBizTitle()
      try {
        this.loading = true
        var url = ''
        if (this.id) {
          url = edit
        } else {
          url = add
        }
        this.model.slipDetailList = this.formData
        const response = await url({
          ...this.model,
        })
        if (response.success) {
          this.$refs.uToast.show({
            message: response.message,
            type: 'default',
            complete() {
              this.isSubmit = false
              if (getCurrentPages().length > 1) {
                uni.navigateBack()
              } else {
                uni.reLaunch({
                  url: '/pages/home/home',
                })
              }
            },
          })
        }
      } finally {
        this.loading = false
      }
    },
    // 获取流程列表
    getProcessList(id) {
      if (this.isSubmit) {
        this.$refs.processConfig.showPopup = true
        this.$refs.processConfig.formUrl = this.formUrl
        this.$refs.processConfig.formUrlMobile = this.formUrlMobile
        this.$refs.processConfig.flowCode = this.flowCode
        this.$refs.processConfig.edit(id, this.processId, this.beanName)
      }
    },
    // 提交流程成功
    onOk() {
      this.$refs.uToast.show({
        message: '提交成功',
        type: 'success',
        complete() {
          if (getCurrentPages().length > 1) {
            uni.navigateBack()
          } else {
            uni.reLaunch({
              url: '/pages/home/home',
            })
          }
        },
      })
    },
  },
  watch: {
    'model.applyCompany'(current, old) {
      if (old && current && old !== current) {
        this.backUpApplyCompany = old
        // this.resetMetaData()
      }
    },
    'model.teamId'(current, old) {
      if (old && current && old !== current) {
        this.backUpTeamId = old
        // this.resetMetaData()
      }
    },
  },
}
</script>

<style scoped lang="scss">
@import url('@/assets/inputStyle.scss');
.trip-form-data {
  ::v-deep {
    .u-form-item__body {
      padding-top: 2px;
      padding-bottom: 2px;
    }
  }
}
.checkbox-item {
  display: flex;
  align-items: center;
}
</style>
